package com.huluobo.a2207kotlindouyin.shop

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.GridLayoutManager
import com.huluobo.a2207kotlindouyin.R
import com.huluobo.a2207kotlindouyin.adapter.ShopAdapter
import com.huluobo.a2207kotlindouyin.cart.CartActivity
import com.huluobo.a2207kotlindouyin.databinding.ActivityShopBinding
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class ShopActivity : BaseActivity<ActivityShopBinding, ShopViewModel>() {
    private lateinit var shopAdapter: ShopAdapter
    override fun initData() {
        vm.getGoods(0, 1, 10)
        vm.getGoodsSuccess.observe(this) {
            shopAdapter.data.clear()
            shopAdapter.data.addAll(it)
            shopAdapter.notifyDataSetChanged()
        }
    }

    override fun initView() {
        binding.shopRv.layoutManager = GridLayoutManager(this, 2)
        shopAdapter = ShopAdapter()
        binding.shopRv.adapter = shopAdapter

        shopAdapter.setOnItemClickListener { adapter, view, position ->
            val goodsId = shopAdapter.data[position].id
            val intent = Intent(this, DetailActivity::class.java)
            intent.putExtra(Const.PARAM_GOODS_ID, goodsId)
            startActivity(intent)
        }

        binding.shopSearchBtn.setOnClickListener {
            val keyword = binding.shopSearchEt.text.toString()
            if (keyword.isNotEmpty()) {
                val newGoodsList = shopAdapter.data.filter {
                    it.goods_desc.contains(keyword, true)
                }
                shopAdapter.data.clear()
                shopAdapter.data.addAll(newGoodsList)
                shopAdapter.notifyDataSetChanged()
            } else {
                vm.getGoods(0, 1, 10)
            }
        }

        binding.shopToCartBtn.setOnClickListener {
            val intent = Intent(this, CartActivity::class.java)
            startActivity(intent)
        }
    }
}